package com.example.eamh2system.netty.handler;

import com.example.eamh2system.netty.ChannelMap;
import com.example.eamh2system.netty.message.ModbusResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.Date;

@Slf4j
@ChannelHandler.Sharable
@Component
public class H2NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        super.channelActive(ctx);
        ChannelMap.getChannelMap().put("1",ctx.channel());
        log.info("active channel={}", ctx.channel() ,"time:{}" , new Date().toLocaleString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 处理接收到的 Modbus 响应消息
        if (msg instanceof ModbusResponse) {
            ModbusResponse response = (ModbusResponse) msg;
            boolean[] coilStatus = response.getCoilStatus();

            System.out.println("Received coil status:");
            for (int i = 0; i < coilStatus.length; i++) {
                System.out.println("Coil " + i + ": " + coilStatus[i]);
            }
        }
    }

}
